<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Gregwar\Captcha\CaptchaBuilder;
use Session, DB, Hash;

class LoginController extends Controller
{
    // 登录页面
    public function login(Request $request)
    {
        $data = $request->old();
        return view("admin.login", compact("data"));
    }

    //验证码
    public function captcha()
    {
        // 生成验证码图片的Builder对象 配置相应的属性
        $builder = new CaptchaBuilder;
        // 可以设置图片的宽高及字体
        $builder->build(100, 32, null);
        // 获取验证码的内容
        $phrase = $builder->getPhrase();


        // 把内容存入session
        Session::flash('code', $phrase);
        // 生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
    }

    //登陆验证
    public function logTodo(Request $request)
    {
//        dd($request);   //DeBug
        //接受数据
        $data = $request->all();
        //验证码是否正确
        if (session("code") != $data["code"]) {
            $request->flash();
            return back()->with(["info" => "验证码错误"]);
        }

        //有效性验证
        $this->validate($request, [
            "uname" => "required",
            "password" => "required|between:6,15",
        ], [
            "uname.required" => "账号未填写",
            "password.required" => "密码不能为空",
            "password.between" => "密码长度应为6-15位"
        ]);

        //真实性验证
        $userRec = DB::table("admin_user")->where("admin_name", $data["uname"])->first();
//		dd($userRec);exit;
        if (empty($userRec))
        {
            $request->flash();
            return back()->with(["info" => "账号不存在"]);
//
        } else if (!Hash::check($data["password"], $userRec->admin_pass))
        {
            $request->flash();
            return back()->with(["info" => "密码错误"]);
        } else {//返回结果
            // 修改登录时间
            $ip = $request->ip();
            $time = date('Y-m-d H:i:s');
            DB::table('admin_user')->where('id', $userRec->id)->update(['admin_logintime'=>$time, 'admin_loginip'=>$ip]);
            // 重新获取
            $userRec = DB::table('admin_user')->where('id', $userRec->id)->first();
            //将用户状态写入session
            session(["adminuserData" => $userRec]);
            // 回首页
            return redirect("/admin");
        }
    }

    //退出登陆
    public function logout()
    {
        //销毁session
        Session::forget("adminuserData");
        return redirect("/admin");
    }
}
